<?php

namespace App\Http\Controllers\Client;

use App\Models\MemberModel;
use App\Services\MemberService;
use App\Utils\ApiResponse;
use App\Utils\JwtUtil;
use Illuminate\Http\Request;

class MemberController extends ClientBase
{
    /**
     * 注册方法
     * @param Request $request
     */
    public function register(Request $request)
    {
        $data = $request->decrypted_data;
        $number = (string) $data->number;
        $passWord = (string) $data->password;
        if (!$number) {
            ApiResponse::fail("用户名不能为空");
        }
        if (!$passWord) {
            ApiResponse::fail("密码不能为空");
        }
        $memberService = new MemberService();
        $memberInfo = $memberService->getMemberInfoByNumber($number);
        if ($memberInfo) {
            ApiResponse::fail("账号已存在");
        }
        $pwdHash = $memberService->passEncode($passWord);
        $newMember = new MemberModel();
        $newMember->number = $number;
        $newMember->password = $pwdHash;
        $newMember->save();
        $token = JwtUtil::getToken([
            'user_id'     => $newMember->id,
            'user_number' => $newMember->number,
        ]);
        ApiResponse::success([
            "user_id" => $newMember->id,
            "token"   => $token
        ]);
    }

    /**
     * 登录
     * @param Request $request
     */
    public function login(Request $request)
    {
        $data = $request->decrypted_data;
        $number = (string) $data->number;
        $passWord = (string) $data->password;
        if (!$number) {
            ApiResponse::fail("用户名不能为空");
        }
        if (!$passWord) {
            ApiResponse::fail("密码不能为空");
        }
        $memberService = new MemberService();
        $memberInfo = $memberService->getMemberInfoByNumber($number);
        if (!$memberInfo) {
            ApiResponse::fail("账号不存在");
        }
        if (!$memberService->passCheck($passWord, $memberInfo->password)) {
            ApiResponse::fail("密码不正确");
        }
        $token = JwtUtil::getToken([
            'user_id'     => $memberInfo->id,
            'user_number' => $memberInfo->number,
        ]);
        ApiResponse::success([
            "token" => $token
        ]);
    }
}
